import { defineStore } from "pinia";
import { ref, watch, computed, type ComputedRef } from "vue";

// 定义颜色配置的接口
interface ThemeColors {
  primary: string;
  primaryDark: string;
  success: string;
  warning: string;
  error: string;
  border: string;
  text: string;
  textSecondary: string;
  background: string;
  componentBackground: string;
  shadowColor: string;
  hoverColor:string;
  borderColor:string;
  highlight:string;
  buttonColor:string;
}

// 定义主题对象的接口
interface Theme {
  id: string;
  name: string;
  icon: string;
  colors: ThemeColors;
  isSystem: boolean;
}

// 定义主题集合类型
type predefinedThemes = {
  [key: string]: Theme;
};

// --primary-100:#566ef2;
// --primary-200:#909cff;
// --primary-300:#feffff;
// --accent-100:#2196F3;
// --accent-200:#003f8f;
// --text-100:#333333;
// --text-200:#5c5c5c;
// --bg-100:#FFFFFF;
// --bg-200:#f5f5f5;
// --bg-300:#cccccc;


// 使用类型断言确保主题配置的正确性
const predefinedThemes: Record<string, Theme> = {
  light: {
    id: "light",
    name: "极简白",
    icon: "fas fa-sun",
    colors: {
      primary: "#fff",
      primaryDark: "#096dd9",
      success: "#52c41a",
      warning: "#faad14",
      error: "#f5222d",
      border: "rgba(30, 30, 30, 0.12)",
      text: "#333333",
      textSecondary: "#666666",
      background: "#f0f2f5",
      componentBackground: "#fffefb",
      shadowColor: "rgba(0, 0, 0, 0.36)",
      hoverColor:"#d4eaf7",
      borderColor:"rgba(30, 30, 30, 0.23)",
      highlight: "rgba(255, 255, 255, 0.2)",
      buttonColor:"#FFD369",

    },
    isSystem: true,
  },
  dark: {
    id: "dark",
    name: "暗黑主题",
    icon: "fas fa-moon",
    colors: {
      primary: " #000000",
      primaryDark: "#0d0d0d",
      success: "#49aa19",
      warning: "#d89614",
      error: "#d32029",
      border: "#303030",
      text: "#e0e0e0",
      textSecondary: "#a0a0a0",
      background: "#141414",
      componentBackground: "#1f1f1f",
      shadowColor: "rgba(0, 0, 0, 0.3)",
      hoverColor:"rgba(0, 0, 0, 0.1)",
      borderColor:"rgba(30, 30, 30, 0.37)",
      highlight: "rgba(255, 255, 255, 0.2)",
      buttonColor:"#d4eaf7",

    },
    isSystem: true,
  },
  blue: {
    id: "blue",
    name: "蓝色主题",
    icon: "fas fa-water",
    colors: {
      primary: "#0052cc",
      primaryDark: "#003d99",
      success: "#36b37e",
      warning: "#ffab00",
      error: "#ff5630",
      border: "#dfe1e6",
      text: "#172b4d",
      textSecondary: "#6b778c",
      background: "#ebf2ff",
      componentBackground: "#ffffff",
      shadowColor: "rgba(0, 82, 204, 0.1)",
      hoverColor:"rgba(0, 0, 0, 0.1)",
      borderColor:"rgba(30, 30, 30, 0.37)",
      highlight: "rgba(255, 255, 255, 0.2)",
      buttonColor:"#d4eaf7",

    },    isSystem: true,
  },
  green: {
    id: "green",
    name: "绿色主题",
    icon: "fas fa-leaf",
    colors: {
      primary: "#2e8b57",
      primaryDark: "#1e5631",
      success: "#3cb371",
      warning: "#f0e68c",
      error: "#cd5c5c",
      border: "#c1e1c1",
      text: "#2e3d2e",
      textSecondary: "#5a6b5a",
      background: "#f0fff0",
      componentBackground: "#ffffff",
      shadowColor: "rgba(46, 139, 87, 0.1)",
      hoverColor:"rgba(0, 0, 0, 0.1)",
      borderColor:"rgba(30, 30, 30, 0.37)",
      highlight: "rgba(255, 255, 255, 0.2)",
      buttonColor:"#d4eaf7",

    },    isSystem: true,
  },
  purple: {
    id: "purple",
    name: "紫色主题",
    icon: "fas fa-gem",
    colors: {
      primary: "#722ed1",
      primaryDark: "#531dab",
      success: "#52c41a",
      warning: "#faad14",
      error: "#f5222d",
      border: "#e8e8e8",
      text: "#333333",
      textSecondary: "#666666",
      background: "#f9f0ff",
      componentBackground: "#ffffff",
      shadowColor: "rgba(114, 46, 209, 0.1)",
      hoverColor:"rgba(0, 0, 0, 0.1)",
      borderColor:"rgba(30, 30, 30, 0.37)",
      highlight: "rgba(255, 255, 255, 0.2)",
      buttonColor:"#d4eaf7",

    },    isSystem: true,
  },
  origin: {
    id: "origin",
    name: "橙色主题",
    icon: "fas fa-gem",
    colors: {
      primary: "#f4fdfd",
      primaryDark: "#531dab",
      success: "#52c41a",
      warning: "#faad14",
      error: "#f5222d",
      border: "#e8e8e8",
      text: "#333333",
      textSecondary: "#666666",
      background: "#ffffff",
      componentBackground: "#ffffff",
      shadowColor: "rgba(114, 46, 209, 0.1)",
      hoverColor:"rgba(0, 0, 0, 0.1)",
      borderColor:"rgba(30, 30, 30, 0.37)",
      highlight: "rgba(255, 255, 255, 0.2)",
      buttonColor:"#d4eaf7",

    },    isSystem: true,
  },
} as const satisfies predefinedThemes;

export const useThemeStore = defineStore("theme", () => {
  // 类型定义
  type ThemeDictionary = Record<string, Theme>;
  type ThemeWithoutSystem = Omit<Theme, "isSystem"> & Partial<Pick<Theme, "isSystem">>;

  // 加载所有主题（预定义 + 自定义）
  const loadThemes = (): ThemeDictionary => {
    const customThemesJson = localStorage.getItem("customThemes");
    const customThemes: ThemeDictionary = customThemesJson ? JSON.parse(customThemesJson) : {};
    return { ...predefinedThemes, ...customThemes };
  };

  // 所有主题
  const themes = ref<ThemeDictionary>(loadThemes());

  // 当前主题ID
  const currentThemeId = ref<string>(localStorage.getItem("themeId") || "light");

  // 自动主题模式
  const autoThemeMode = ref<boolean>(localStorage.getItem("autoThemeMode") === "true");

  // 计算属性：获取当前主题对象
  const currentTheme: ComputedRef<Theme> = computed(() =>
    themes.value[currentThemeId.value] || predefinedThemes.light
  );

  // 获取所有可用主题
  const availableThemes = computed<Theme[]>(() => Object.values(themes.value));

  // 系统主题
  const systemThemes = computed<Theme[]>(() =>
    Object.values(themes.value).filter((theme) => theme.isSystem)
  );

  // 自定义主题
  const customThemes = computed<Theme[]>(() =>
    Object.values(themes.value).filter((theme) => !theme.isSystem)
  );

  // 设置主题
  const setTheme = (themeId: string): void => {
    if (themes.value[themeId]) {
      currentThemeId.value = themeId;
      localStorage.setItem("themeId", themeId);
      applyTheme();
    }
  };

  // 切换暗黑模式
  const toggleDarkMode = (): void => {
    const newThemeId = currentThemeId.value === "dark" ? "light" : "dark";
    setTheme(newThemeId);
  };

  // 设置自动主题模式
  const setAutoThemeMode = (value: boolean): void => {
    autoThemeMode.value = value;
    localStorage.setItem("autoThemeMode", value.toString());

    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    const listener = () => applySystemTheme();

    if (value) {
      applySystemTheme();
      mediaQuery.addEventListener("change", listener);
    } else {
      mediaQuery.removeEventListener("change", listener);
    }
  };

  // 应用系统主题
  const applySystemTheme = (): void => {
    const isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
    setTheme(isDarkMode ? "dark" : "light");
  };

  // 创建自定义主题
  const createCustomTheme = (theme: Omit<ThemeWithoutSystem, "id">): string => {
    const id = `custom_${Date.now()}`;
    const newTheme: Theme = {
      ...theme,
      id,
      isSystem: false,
    };

    themes.value = { ...themes.value, [id]: newTheme };
    saveCustomThemes();
    return id;
  };

  // 更新自定义主题
  const updateCustomTheme = (id: string, updates: Partial<Theme>): boolean => {
    const theme = themes.value[id];
    if (theme && !theme.isSystem) {
      themes.value[id] = { ...theme, ...updates };
      if (currentThemeId.value === id) applyTheme();
      saveCustomThemes();
      return true;
    }
    return false;
  };

  // 删除自定义主题
  const deleteCustomTheme = (id: string): boolean => {
    if (themes.value[id] && !themes.value[id].isSystem) {
      if (currentThemeId.value === id) setTheme("light");
      const { [id]: removed, ...rest } = themes.value;
      themes.value = rest;
      saveCustomThemes();
      return true;
    }
    return false;
  };

  // 保存自定义主题到localStorage
  const saveCustomThemes = (): void => {
    const customThemesObj = Object.values(themes.value)
      .filter(theme => !theme.isSystem)
      .reduce((acc, theme) => ({ ...acc, [theme.id]: theme }), {});
    localStorage.setItem("customThemes", JSON.stringify(customThemesObj));
  };

  // 导出主题
  const exportTheme = (id: string): string | null => {
    const theme = themes.value[id];
    return theme ? JSON.stringify(theme) : null;
  };

  // 导入主题
  const importTheme = (themeJson: string): string | null => {
    try {
      const parsed = JSON.parse(themeJson) as ThemeWithoutSystem;
      if (parsed.colors && parsed.name) {
        return createCustomTheme({
          name: parsed.name,
          icon: parsed.icon || "fas fa-palette",
          colors: parsed.colors,
        });
      }
    } catch (e) {
      console.error("导入主题失败:", e);
    }
    return null;
  };

  // 应用当前主题到文档
  const applyTheme = (): void => {
    const theme = themes.value[currentThemeId.value];
    if (!theme) return;

    // 应用暗黑类
    document.documentElement.classList.toggle("dark", currentThemeId.value === "dark");

    // 应用CSS变量
    const root = document.documentElement;
    Object.entries(theme.colors).forEach(([key, value]) => {
      const cssKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
      root.style.setProperty(`--${cssKey}`, value);
    });
  };

  // 初始化主题
  const initTheme = (): void => {
    if (autoThemeMode.value) {
      applySystemTheme();
      window.matchMedia("(prefers-color-scheme: dark)")
        .addEventListener("change", applySystemTheme);
    } else {
      applyTheme();
    }
  };

  // 监听主题变化
  watch(currentThemeId, applyTheme);

  return {
    themes,
    currentThemeId,
    currentTheme,
    availableThemes,
    systemThemes,
    customThemes,
    autoThemeMode,
    setTheme,
    toggleDarkMode,
    setAutoThemeMode,
    createCustomTheme,
    updateCustomTheme,
    deleteCustomTheme,
    exportTheme,
    importTheme,
    initTheme,
  };
});
